package com.heima.utils.common;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwsHeader;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @BelongsProject: my
 * @BelongsPackage: com.heima.utils.common
 * @Author: ji ge
 * @CreateTime: 2024-02-06  14:14
 * @Description: TODO
 * @Version: 1.0
 */
public class AppJwtUtil {
    // TOKEN的有效期一天（S）
    private static final int TOKEN_TIME_OUT = 3_600;
    // 加密KEY
    private static final String TOKEN_ENCRY_KEY = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY";
    // 最小刷新间隔(S)
    private static final int REFRESH_TIME = 300;

    public static String getToken(Long id){
        Map<String, Object> claimMaps = new HashMap<>();
        claimMaps.put("id",id);
        long currentTime = System.currentTimeMillis();
        return Jwts.builder()
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(new Date(currentTime))  //签发时间
                .setSubject("system")  //说明
                .setIssuer("heima") //签发者信息
                .setAudience("app")  //接收用户
                .compressWith(CompressionCodecs.GZIP)  //数据压缩方式
                .signWith(SignatureAlgorithm.HS512, generalKey()) //加密方式
                .setExpiration(new Date(currentTime + TOKEN_TIME_OUT * 1000))  //过期时间戳
                .addClaims(claimMaps) //cla信息
                .compact();
    }

    private static SecretKey generalKey() {
        byte[] encode = Base64.getEncoder().encode(TOKEN_ENCRY_KEY.getBytes());
        return  new SecretKeySpec(encode,0,encode.length,"AES");
    }

    private static Jws<Claims> getJws(String token){
        return Jwts.parser().setSigningKey(generalKey()).parseClaimsJws(token);
    }

    private static Claims getClaimsBody(String token){
        return getJws(token).getBody();

    }
    private static JwsHeader getHeaderBody(String token){
        return getJws(token).getHeader();
    }
    public static int verifyToken(Claims claims){
        if (claims == null) {
            return 1;
        }
        boolean before = claims.getExpiration().before(new Date());
        // 需要自动刷新TOKEN
        if((claims.getExpiration().getTime()-System.currentTimeMillis())>REFRESH_TIME*1000){
            return -1;
        }else {
            return 0;
        }
    }
}
